#!/bin/bash
# Gitee 专用工具链下载脚本

echo "📥 从国内镜像下载工具链..."

TOOLCHAIN_DIR="$PWD/toolchains"
mkdir -p $TOOLCHAIN_DIR
cd $TOOLCHAIN_DIR

# 1. 下载 AOSP Clang (Gitee 镜像)
echo "下载 AOSP Clang 工具链..."
if [ ! -d "aosp-clang" ]; then
    echo "从 Gitee 下载 Clang..."
    git clone --depth=1 https://gitee.com/mirrors/proton-clang.git aosp-clang
else
    echo "Clang 已存在，跳过下载"
fi

# 2. 下载 GCC 工具链 (国内镜像)
echo "下载 GCC 交叉编译工具链..."

# ARM64 GCC - 使用清华镜像
if [ ! -d "gcc-arm64" ]; then
    echo "下载 ARM64 GCC..."
    wget -q --timeout=60 https://mirrors.tuna.tsinghua.edu.cn/linaro-components/toolchain/binaries/latest-7/aarch64-linux-gnu/gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz
    if [ $? -eq 0 ]; then
        tar -xf gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz
        mv gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu gcc-arm64
        rm gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz
    else
        echo "⚠️  下载失败，尝试备用镜像..."
        wget -q https://releases.linaro.org/components/toolchain/binaries/latest-7/aarch64-linux-gnu/gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz
        if [ $? -eq 0 ]; then
            tar -xf gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz
            mv gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu gcc-arm64
            rm gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz
        fi
    fi
fi

# ARM GCC - 使用清华镜像
if [ ! -d "gcc-arm" ]; then
    echo "下载 ARM GCC..."
    wget -q --timeout=60 https://mirrors.tuna.tsinghua.edu.cn/linaro-components/toolchain/binaries/latest-7/arm-linux-gnueabi/gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi.tar.xz
    if [ $? -eq 0 ]; then
        tar -xf gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi.tar.xz
        mv gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi gcc-arm
        rm gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi.tar.xz
    else
        echo "⚠️  下载失败，尝试备用镜像..."
        wget -q https://releases.linaro.org/components/toolchain/binaries/latest-7/arm-linux-gnueabi/gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi.tar.xz
        if [ $? -eq 0 ]; then
            tar -xf gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi.tar.xz
            mv gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi gcc-arm
            rm gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabi.tar.xz
        fi
    fi
fi

# 3. 下载 AnyKernel3 (Gitee 镜像)
echo "下载 AnyKernel3..."
if [ ! -d "AnyKernel3" ]; then
    git clone --depth=1 https://gitee.com/mirrors/AnyKernel3.git
else
    echo "AnyKernel3 已存在，跳过下载"
fi

# 4. 下载内核源码 (Gitee 镜像)
echo "下载内核源码..."
if [ ! -d "kernel-source" ]; then
    # 这里可以添加具体的内核源码 Gitee 镜像
    echo "提示: 请手动克隆内核源码到 kernel-source 目录"
    echo "例如: git clone https://gitee.com/your-mirror/kernel-source.git"
else
    echo "内核源码已存在"
fi

echo "✅ 工具链下载完成"
echo "📁 工具链目录: $TOOLCHAIN_DIR"
ls -la $TOOLCHAIN_DIR
